#ifndef SEMINIX_WAIT_H
#define SEMINIX_WAIT_H

#include <utils/stddef.h>
#include <utils/list.h>
#include <seminix/spinlock.h>
#include <seminix/sched.h>

/* First argument to waitid: */
#define P_ALL		0
#define P_PID		1
#define P_PGID		2

typedef struct __wait_queue wait_queue_t;
typedef int (*wait_queue_func_t)(wait_queue_t *wait, unsigned mode, int sync, void *key);
extern int default_wake_function(wait_queue_t *wait, unsigned mode, int sync, void *key);

struct __wait_queue {
    unsigned int flags;
#define WQ_FLAG_EXCLUSIVE	0x01
    void *private;
    wait_queue_func_t func;
    struct list_head task_list;
};

struct __wait_queue_head {
    spinlock_t lock;
    struct list_head task_list;
};
typedef struct __wait_queue_head wait_queue_head_t;

struct tcb;

/*
 * Macros for declaration and initialisaton of the datatypes
 */

#define __WAITQUEUE_INITIALIZER(name, tsk) {				\
    .private	= tsk,						\
    .func		= default_wake_function,			\
    .task_list	= { NULL, NULL } }

#define DECLARE_WAITQUEUE(name, tsk)					\
    wait_queue_t name = __WAITQUEUE_INITIALIZER(name, tsk)

#define __WAIT_QUEUE_HEAD_INITIALIZER(name) {				\
    .lock		= __SPIN_LOCK_UNLOCKED(name.lock),		\
    .task_list	= { &(name).task_list, &(name).task_list } }

#define DECLARE_WAIT_QUEUE_HEAD(name) \
    wait_queue_head_t name = __WAIT_QUEUE_HEAD_INITIALIZER(name)

extern void init_waitqueue_head(wait_queue_head_t *q);

#define DECLARE_WAIT_QUEUE_HEAD_ONSTACK(name) DECLARE_WAIT_QUEUE_HEAD(name)

static inline void init_waitqueue_entry(wait_queue_t *q, struct tcb *p)
{
    q->flags = 0;
    q->private = p;
    q->func = default_wake_function;
}

static inline void init_waitqueue_func_entry(wait_queue_t *q,
                    wait_queue_func_t func)
{
    q->flags = 0;
    q->private = NULL;
    q->func = func;
}

static inline int waitqueue_active(wait_queue_head_t *q)
{
    return !list_empty(&q->task_list);
}

/*
 * Used to distinguish between sync and async io wait context:
 * sync i/o typically specifies a NULL wait queue entry or a wait
 * queue entry bound to a task (current task) to wake up.
 * aio specifies a wait queue entry with an async notification
 * callback routine, not associated with any task.
 */
#define is_sync_wait(wait)	(!(wait) || ((wait)->private))

extern void add_wait_queue(wait_queue_head_t *q, wait_queue_t * wait);
extern void add_wait_queue_exclusive(wait_queue_head_t *q, wait_queue_t * wait);
extern void remove_wait_queue(wait_queue_head_t *q, wait_queue_t * wait);

static inline void __add_wait_queue(wait_queue_head_t *head, wait_queue_t *new)
{
    list_add(&new->task_list, &head->task_list);
}

/*
 * Used for wake-one threads:
 */
static inline void __add_wait_queue_tail(wait_queue_head_t *head,
                        wait_queue_t *new)
{
    list_add_tail(&new->task_list, &head->task_list);
}

static inline void __remove_wait_queue(wait_queue_head_t *head,
                            wait_queue_t *old)
{
    list_del(&old->task_list);
}

void __wake_up(wait_queue_head_t *q, unsigned int mode, int nr, void *key);
extern void __wake_up_locked(wait_queue_head_t *q, unsigned int mode);
extern void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr);

#define wake_up(x)			__wake_up(x, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE, 1, NULL)
#define wake_up_nr(x, nr)		__wake_up(x, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE, nr, NULL)
#define wake_up_all(x)			__wake_up(x, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE, 0, NULL)
#define wake_up_interruptible(x)	__wake_up(x, TASK_INTERRUPTIBLE, 1, NULL)
#define wake_up_interruptible_nr(x, nr)	__wake_up(x, TASK_INTERRUPTIBLE, nr, NULL)
#define wake_up_interruptible_all(x)	__wake_up(x, TASK_INTERRUPTIBLE, 0, NULL)
#define	wake_up_locked(x)		__wake_up_locked((x), TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE)
#define wake_up_interruptible_sync(x)   __wake_up_sync((x),TASK_INTERRUPTIBLE, 1)

#define __wait_event(wq, condition) 					\
do {									\
    DEFINE_WAIT(__wait);						\
                                    \
    for (;;) {							\
        prepare_to_wait(&wq, &__wait, TASK_UNINTERRUPTIBLE);	\
        if (condition)						\
            break;						\
        schedule();						\
    }								\
    finish_wait(&wq, &__wait);					\
} while (0)

/**
 * wait_event - sleep until a condition gets true
 * @wq: the waitqueue to wait on
 * @condition: a C expression for the event to wait for
 *
 * The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
 * @condition evaluates to true. The @condition is checked each time
 * the waitqueue @wq is woken up.
 *
 * wake_up() has to be called after changing any variable that could
 * change the result of the wait condition.
 */
#define wait_event(wq, condition) 					\
do {									\
    if (condition)	 						\
        break;							\
    __wait_event(wq, condition);					\
} while (0)

#define __wait_event_timeout(wq, condition, ret)			\
do {									\
    DEFINE_WAIT(__wait);						\
                                    \
    for (;;) {							\
        prepare_to_wait(&wq, &__wait, TASK_UNINTERRUPTIBLE);	\
        if (condition)						\
            break;						\
        ret = schedule_timeout(ret);				\
        if (!ret)						\
            break;						\
    }								\
    finish_wait(&wq, &__wait);					\
} while (0)

/**
 * wait_event_timeout - sleep until a condition gets true or a timeout elapses
 * @wq: the waitqueue to wait on
 * @condition: a C expression for the event to wait for
 * @timeout: timeout, in jiffies
 *
 * The process is put to sleep (TASK_UNINTERRUPTIBLE) until the
 * @condition evaluates to true. The @condition is checked each time
 * the waitqueue @wq is woken up.
 *
 * wake_up() has to be called after changing any variable that could
 * change the result of the wait condition.
 *
 * The function returns 0 if the @timeout elapsed, and the remaining
 * jiffies if the condition evaluated to true before the timeout elapsed.
 */
#define wait_event_timeout(wq, condition, timeout)			\
({									\
    long __ret = timeout;						\
    if (!(condition)) 						\
        __wait_event_timeout(wq, condition, __ret);		\
    __ret;								\
})

#define __wait_event_interruptible(wq, condition, ret)			\
do {									\
    DEFINE_WAIT(__wait);						\
                                    \
    for (;;) {							\
        prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE);	\
        if (condition)						\
            break;						\
        if (!signal_pending(current)) {				\
            schedule();					\
            continue;					\
        }							\
        ret = -ERESTART;					\
        break;							\
    }								\
    finish_wait(&wq, &__wait);					\
} while (0)

/**
 * wait_event_interruptible - sleep until a condition gets true
 * @wq: the waitqueue to wait on
 * @condition: a C expression for the event to wait for
 *
 * The process is put to sleep (TASK_INTERRUPTIBLE) until the
 * @condition evaluates to true or a signal is received.
 * The @condition is checked each time the waitqueue @wq is woken up.
 *
 * wake_up() has to be called after changing any variable that could
 * change the result of the wait condition.
 *
 * The function will return -ERESTART if it was interrupted by a
 * signal and 0 if @condition evaluated to true.
 */
#define wait_event_interruptible(wq, condition)				\
({									\
    int __ret = 0;							\
    if (!(condition))						\
        __wait_event_interruptible(wq, condition, __ret);	\
    __ret;								\
})

#define __wait_event_interruptible_timeout(wq, condition, ret)		\
do {									\
    DEFINE_WAIT(__wait);						\
                                    \
    for (;;) {							\
        prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE);	\
        if (condition)						\
            break;						\
        if (!signal_pending(current)) {				\
            ret = schedule_timeout(ret);			\
            if (!ret)					\
                break;					\
            continue;					\
        }							\
        ret = -ERESTART;					\
        break;							\
    }								\
    finish_wait(&wq, &__wait);					\
} while (0)

/**
 * wait_event_interruptible_timeout - sleep until a condition gets true or a timeout elapses
 * @wq: the waitqueue to wait on
 * @condition: a C expression for the event to wait for
 * @timeout: timeout, in jiffies
 *
 * The process is put to sleep (TASK_INTERRUPTIBLE) until the
 * @condition evaluates to true or a signal is received.
 * The @condition is checked each time the waitqueue @wq is woken up.
 *
 * wake_up() has to be called after changing any variable that could
 * change the result of the wait condition.
 *
 * The function returns 0 if the @timeout elapsed, -ERESTART if it
 * was interrupted by a signal, and the remaining jiffies otherwise
 * if the condition evaluated to true before the timeout elapsed.
 */
#define wait_event_interruptible_timeout(wq, condition, timeout)	\
({									\
    long __ret = timeout;						\
    if (!(condition))						\
        __wait_event_interruptible_timeout(wq, condition, __ret); \
    __ret;								\
})

#define __wait_event_interruptible_exclusive(wq, condition, ret)	\
do {									\
    DEFINE_WAIT(__wait);						\
                                    \
    for (;;) {							\
        prepare_to_wait_exclusive(&wq, &__wait,			\
                    TASK_INTERRUPTIBLE);		\
        if (condition)						\
            break;						\
        if (!signal_pending(current)) {				\
            schedule();					\
            continue;					\
        }							\
        ret = -ERESTART;					\
        break;							\
    }								\
    finish_wait(&wq, &__wait);					\
} while (0)

#define wait_event_interruptible_exclusive(wq, condition)		\
({									\
    int __ret = 0;							\
    if (!(condition))						\
        __wait_event_interruptible_exclusive(wq, condition, __ret);\
    __ret;								\
})

/*
 * Must be called with the spinlock in the wait_queue_head_t held.
 */
static inline void add_wait_queue_exclusive_locked(wait_queue_head_t *q,
                           wait_queue_t * wait)
{
    wait->flags |= WQ_FLAG_EXCLUSIVE;
    __add_wait_queue_tail(q,  wait);
}

/*
 * Must be called with the spinlock in the wait_queue_head_t held.
 */
static inline void remove_wait_queue_locked(wait_queue_head_t *q,
                        wait_queue_t * wait)
{
    __remove_wait_queue(q,  wait);
}

/*
 * These are the old interfaces to sleep waiting for an event.
 * They are racy.  DO NOT use them, use the wait_event* interfaces above.
 * We plan to remove these interfaces.
 */
extern void sleep_on(wait_queue_head_t *q);
extern long sleep_on_timeout(wait_queue_head_t *q,
                      signed long timeout);
extern void interruptible_sleep_on(wait_queue_head_t *q);
extern long interruptible_sleep_on_timeout(wait_queue_head_t *q,
                       signed long timeout);

/*
 * Waitqueues which are removed from the waitqueue_head at wakeup time
 */
void prepare_to_wait(wait_queue_head_t *q,
                wait_queue_t *wait, int state);
void prepare_to_wait_exclusive(wait_queue_head_t *q,
                wait_queue_t *wait, int state);
void finish_wait(wait_queue_head_t *q, wait_queue_t *wait);
int autoremove_wake_function(wait_queue_t *wait, unsigned mode, int sync, void *key);

#define DEFINE_WAIT(name)						\
    wait_queue_t name = {						\
        .private	= current,				\
        .func		= autoremove_wake_function,		\
        .task_list	= LIST_HEAD_INIT((name).task_list),	\
    }

#define init_wait(wait)							\
    do {								\
        (wait)->private = current;				\
        (wait)->func = autoremove_wake_function;		\
        INIT_LIST_HEAD(&(wait)->task_list);			\
    } while (0)

#endif /* !SEMINIX_WAIT_H */
